<template>
	<view class="app-pay">
		<view class="person-info">
			<view class="info-wrapper">
				<text>{{ order_info.name || '体检人' }}</text>
				<text>{{ order_info.certificatenumber || '证件号码' }}</text>
			</view>
			<!-- <image :src="imgUrl('/static/img/icons/edit-icon-active.png')" mode="aspectFill" @click="editPersonInfo" /> -->
		</view>

		<view class="case-info">
			<text class="case-title">{{ order_info.storename || '体检机构' }}</text>
			<view class="case-date">
				{{ order_info.appointmentdate}}&nbsp;&nbsp;{{order_info.examtime}}
			</view>

			<view class="case-wrapper">
				<image :src="imgUrl('/static/img/imgs/order-img.png')" mode="aspectFill" />
				<view class="info-wrapper">
					<view class="info-row">
						<!-- <text>{{ orderStore.selectedPackage?.name || '体检套餐' }}</text> -->
						<text>{{ addon_info?.title || '体检套餐' }}</text>
						<text>x1</text>
					</view>
					<text>{{ order_info.brand_title || '品牌机构' }}</text>
				</view>
			</view>

			<view class="case-row" v-if="addon_info.name">
				<text>加项：{{ addon_info.name }}</text>
				<text>￥{{ (addon_info.price) }}</text>
			</view>
		</view>

		<view class="price-info">
			<text class="price-title">价格明细</text>
			<view class="price-row">
				<text>套餐价格</text>
				<text>￥{{ (order_info.packageprice) }}</text>
			</view>
			<view v-if="order_info.addprice > 0" class="price-row">
				<text>加项费用</text>
				<text>￥{{ (order_info.addprice) }}</text>
			</view>
			<view class="price-bottom">
				<text>合计：</text>
				<text>￥{{ (order_info.addprice+order_info.packageprice)}}</text>
			</view>
		</view>
		<view class="button-group" v-if="order_info.paystatus === 0">
			<view class="button-item" @click="goback">返回</view>
			<view class="button-item" style="background:#f54730" @click="cancelApply"
				v-if="order_info.status == 2||order_info.status == 1">{{cancelLoading?'处理中...':"取消预约"}}</view>
			<view class="button-item" @click.stop="goPay">
				去支付
				<text v-if="count_time" style="margin-left:10rpx">{{count_time}}</text>
			</view>
		</view>
		<view class="button-group" v-else>
			<view class="button-item" @click="goback">返回</view>
			<!-- <view class="button-item" style="background:#f54730" @click="changeApply" v-if="order_info.status == 2">改约
			</view> -->
			<view class="button-item" @click="cancelApply" v-if="order_info.status == 2||order_info.status == 1">
				{{cancelLoading?'处理中...':"取消预约"}}
			</view>
		</view>
		<view class="tip-info" style="display:none">
			<text class="tip-title">检前小贴士</text>
			<view class="tip-content">
				<view class="tip-margin">1.建议你当天请禁食、空腹，前一天晚餐后请勿再进食（晚8点后）。否则将影响体检结果的准确性。</view>
				<view class="tip-margin">2.未经过预约，原则上不能体检。检前请确认参检的门店和日期与预约时选择的门店日期一致。</view>
				<view class="tip-margin">3.请携带身份证参检。预约时请填写完成18位身份证号码。</view>
				<view class="tip-margin">4.做胸片检查时，请勿穿有金属饰物、纽扣的衣物，摘取项链、耳环，不要随身携带手机、钢笔、钥匙等金属物品。</view>
				<view class="tip-margin">5.女士要注意避开月经期，否则将影响体检结果的准确性。</view>
				<view class="tip-margin">6.避免在体检过程中造成不必要的问题，请无性生活女性不要妇科检查。怀孕女性及备孕女性禁止做胸片等放射性检查。</view>
				<view class="tip-margin">7.请主动告知现场医护人员身体上的异常状况，或已患疾病、手术史。切勿心存侥幸医生的心态，与自己的健康开玩笑。</view>
				<view class="tip-margin">8.为保证您在体检过程中的舒适度，当您完成抽血和其他空腹体检项目后，建议即先享用体检中心提供的免费早餐，再做剩余项目，以免出现低血糖。请以个人实际情况操作。
				</view>
				<view class="tip-margin">9.出于人身安全考虑，建议老年人及行动不便的人士，由亲友陪同参检。</view>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		computed,
		onMounted,
		nextTick,
		onUnmounted
	} from 'vue'
	import {
		imgUrl,
		miniPay
	} from "../../../utils/global";
	import moment from "moment"
	import {
		useOrderStore
	} from '@/store/order';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		getOrderById,
		cancelOrderApi
	} from '@/api/order';
	import {
		getCaseDetailApi,
		getCaseAddonListApi,
		mNcancelReservationApi,
		pHsetcheckApi,
		pHdeleteinfoApi,
		getCaseAddonByIdApi
	} from '@/api/case';
	import {
		addReserveApi,
		wxPayApi,
		wxRefundApi,
		upPaymentStatus
	} from '@/api/reserve';
	import {
		useUserStore
	} from '@/store/user';
	const orderStore = useOrderStore();
	const userStore = useUserStore();
	const orderDate = ref(new Date());
	const cancel_loading = ref(false)
	// 计算总价
	// const totalPrice = computed(() => {
	// 	let total = orderStore.selectedPackage?.price || 0;
	// 	total += orderStore.selectedAddons.reduce((sum, addon) => sum + addon.price, 0);
	// 	return total;
	// });
	const callBack = ref(null)
	const count_time = ref("")
	onUnmounted(() => {
		if (callBack.value) {
			clearInterval(callBack.value)
			callBack.value = null
			console.log("倒计时暂停")
		}
	})
	// 倒计时
	const countdown = (paydate) => {
		let later_time = moment(paydate).add(15, 'minutes')

		let present_time = moment()
		var duration = moment.duration(later_time.diff(present_time)); // 计算剩余时间
		var hours = duration.hours(); // 获取小时数
		var minutes = duration.minutes(); // 获取分钟数
		var seconds = duration.seconds(); // 获取秒数
		count_time.value = `${minutes<10?'0'+minutes:minutes}:${seconds<10?'0'+seconds:seconds}`
		if (present_time >= later_time) { // 如果当前时间大于或等于未来时间，停止倒计时
			clearInterval(callBack.value);
			callBack.value = null
			count_time.value = ""
		}
		console.log(count_time.value)
	}
	const goback = () => {
		uni.redirectTo({
			url: "/pages/reserve/index/index"
		})
	}
	const order_info = ref({})
	const addon_info = ref({
		name: "",
		title: "",
		price: ""
	})
	onLoad(async (options) => {
		await nextTick();
		if (typeof options.id !== 'undefined') {
			try {
				getDetail(options)
			} catch (error) {}
		}
		// 更新支付信息
		// orderStore.updatePaymentInfo({
		// 	totalAmount: totalPrice.value,
		// 	finalAmount: totalPrice.value
		// });
	});
	const id_info = ref("")
	const getDetail = async (options) => {
		id_info.value = options.id
		const data = await getOrderById({
			id: Number(options.id)
		});
		if (data.additionsid) {
			addon_info.value = await getCaseAddonByIdApi({
				additionsid: data.additionsid
			})
		}
		if ((Number(data.addprice) + Number(data.packageprice)) == 0 && data.paystatus == 0) {
			upPaymentStatus({
				bookingno: data.bookingno
			}).then(() => {
				getDetail(options)
			})
			return
		}
		if (data.paystatus == 0) {
			uni.showToast({
				title: "手动取消或者15分钟不付款默认自动取消",
				icon: "none"
			})
			if (callBack.value) {
				clearInterval(callBack.value)
				callBack.value = null
			}
			callBack.value = setInterval(() => {
				countdown(data.paydate)
			}, 1000)
		}
		data.packageprice = Number(data.packageprice)
		data.addprice = Number(data.addprice)
		data.brand_list = data.brandid.split(",")
		if (typeof data.brand_list == 'string' && data.brand_list) {
			data.brand_list = [data.brand_list]
		}
		data.brand_title = ""
		// 美年
		if (data.brand_list.includes("2")) {
			data.brand_title = "美年"
		}
		// 瑞慈
		if (data.brand_list.includes("1")) {
			data.brand_title = "瑞慈"
		}
		// 普潓
		if (data.brand_list.includes("3")) {
			data.brand_title = "普潓"
		}
		order_info.value = data
		orderStore.setOrder({
			id: data.id,
			reserveNo: data.reserveno,
			status: data.status,
			paystatus: data.paystatus,
			bookingno: data.bookingno
		});
		orderDate.value = new Date(data.creationdate);
		// 如果拿到数据，则设置到 orderStore中
		if ([2, 3].includes(data.status)) {
			orderStore.setCustomerInfo({
				id: data.id,
				planId: data.planid,
				name: data.name,
				phone: data.phonenumber,
				license_type: Number(data.certificatetype),
				license_number: data.certificatenumber,
				gender: data.gender,
				address_area: data.address[0],
				address_detail: data.address[1]
			});
			// orderStore.setPackage({
			// 	price: Number(data.packageprice)
			// });

			orderStore.setOrganization({
				storeId: data.storeid,
				name: data.storename,
				examDate: data.appointmentdate,
				examtime: data.examtime
			});
		}
	}
	// 去支付
	const goPay = async () => {
		try {
			// 如果支付价格为零,就调用更新接口
			if ((Number(order_info.value.addprice) + Number(order_info.value.packageprice)) == 0) {
				upPaymentStatus({
					bookingno: order_info.value.bookingno,
				}).then(() => {
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
				})
				return
			}
			wxPayApi({
				bookingno: order_info.value.bookingno,
				price: (Number(order_info.value.addprice) + Number(order_info.value.packageprice)),
				uid: userStore.userInfo.id,
			}).then(pay_res => {
				miniPay(pay_res).then(result => {
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
				}).catch(err => {})
			})
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: '订单创建失败',
				icon: 'error'
			});
		}
	};

	// 编辑体检人信息
	const editPersonInfo = () => {
		uni.navigateTo({
			url: '/pages/reserve/select/index'
		});
	};

	// 改约
	const changeApply = () => {
		console.log(orderStore.order.bookingno)
		uni.navigateTo({
			url: '/pages/case/orgnization/index?type=1'
		});
	};
	const cancelLoading = ref(false)
	// 普惠取消预约
	const pHcancelReservation = () => {
		cancelLoading.value = true
		pHdeleteinfoApi({
			bookingno: order_info.value.bookingno
		}).then(() => {
			pHsetcheckApi({
				id: order_info.value.id,
				status: "2",
				storeid: order_info.value.storeid,
				storename: order_info.value.storename,
				examDate: order_info.value.appointmentdate,
			}).then(() => {
				// 价格为零就直接取消，不调用接口
				if (((Number(order_info.value.addprice) + Number(order_info.value
						.packageprice)) == 0) || order_info.value.paystatus == 0) {
					
					uni.showToast({
						title: '取消成功',
						icon: 'success'
					});
					setTimeout(() => {
						cancelLoading.value = false
						uni.redirectTo({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
					return
				}
				if (order_info.value.paystatus != 0) {
					wxRefundApi({
						bookingno: order_info.value.bookingno,
						price: (Number(order_info.value.addprice) + Number(
							order_info.value.packageprice)),
					}).then(res => {
						
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						});
						setTimeout(() => {
							cancelLoading.value = false
							uni.redirectTo({
								url: '/pages/reserve/index/index'
							});
						}, 1000);
					}).catch(err => {
						cancelLoading.value = false
					})
				}
			}).catch(err => {
				cancelLoading.value = false
			})
		})

	}
	// 美年取消预约
	const mNcancelReservation = () => {
		cancelLoading.value = true
		mNcancelReservationApi({
			id: order_info.value.id
		}).then(() => {
			// 价格为零就直接取消，不调用接口
			if (((Number(order_info.value.addprice) + Number(order_info.value
					.packageprice)) == 0) || order_info.value.paystatus == 0) {
				uni.showToast({
					title: '取消成功',
					icon: 'success'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/reserve/index/index'
					});
					cancelLoading.value = false
				}, 1000);
				return
			}
			if (order_info.value.paystatus != 0) {
				wxRefundApi({
					bookingno: order_info.value.bookingno,
					price: (Number(order_info.value.addprice) + Number(
						order_info.value.packageprice)),
				}).then(res => {
					uni.showToast({
						title: '取消成功',
						icon: 'success'
					});
					setTimeout(() => {
						cancelLoading.value = false
						uni.redirectTo({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
				}).catch(err => {
					cancelLoading.value = false
				})
			}
		}).catch(err => {
			cancelLoading.value = false
		})
	}
	// 瑞慈取消预约
	const rCcancelReservation = () => {
		console.log(order_info.value.reserveno, "order_info.value.reserveno")
		try {
			cancelLoading.value = true
			cancelOrderApi({
				reserveNo: order_info.value.reserveno,
				bookingno: order_info.value.bookingno,
				type:"xcx",
			}).then(() => {
				// 价格为零就直接取消，不调用接口
				if (((Number(order_info.value.addprice) + Number(order_info.value
						.packageprice)) == 0) || order_info.value.paystatus == 0) {
					uni.showToast({
						title: '取消成功',
						icon: 'success'
					});
					setTimeout(() => {
						cancelLoading.value = false
						uni.redirectTo({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
					return
				}
				if (order_info.value.paystatus != 0) {
					wxRefundApi({
						bookingno: order_info.value.bookingno,
						price: (Number(order_info.value.addprice) + Number(
							order_info.value.packageprice)),
						type:"xcx",
					}).then(res => {
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						});
						setTimeout(() => {
							cancelLoading.value = false
							uni.redirectTo({
								url: '/pages/reserve/index/index'
							});
						}, 1000);
					}).catch(err => {
						cancelLoading.value = false
					})
				}

			}).catch(err => {
				cancelLoading.value = false
			})
		} catch (error) {
			cancelLoading.value = false
		}
	}
	// 取消预约
	const cancelApply = () => {
		if (cancelLoading.value) return
		uni.showModal({
			title: '取消预约',
			content: '你确定要取消本次预约吗?',
			cancelText: '返回',
			confirmText: '确认',
			success: async (res) => {
				if (res.confirm) {
					const data = await getOrderById({
						id: Number(id_info.value)
					});
					data.packageprice = Number(data.packageprice)
					data.addprice = Number(data.addprice)
					data.brand_list = data.brandid.split(",")
					if (typeof data.brand_list == 'string' && data.brand_list) {
						data.brand_list = [data.brand_list]
					}
					data.brand_title = ""
					// 美年
					if (data.brand_list.includes("2")) {
						data.brand_title = "美年"
					}
					// 瑞慈
					if (data.brand_list.includes("1")) {
						data.brand_title = "瑞慈"
					}
					// 普潓
					if (data.brand_list.includes("3")) {
						data.brand_title = "普潓"
					}
					order_info.value = data
					// 美年
					if (order_info.value.brand_list.includes("2")) {
						mNcancelReservation()
						return
					}
					// 瑞慈
					if (order_info.value.brand_list.includes("1")) {
						rCcancelReservation()
						return
					}
					// 普惠
					if (order_info.value.brand_list.includes("3")) {
						pHcancelReservation()
						return
					}
				}
			},

		});
	};
</script>

<style src="./style.scss" scoped />